package com.item.frame;

import com.base.api.MobileInfo;
import com.base.security.entity.ShiroRight;
import com.base.security.entity.ShiroRole;
import com.base.security.shiro.CaptchaEnum;
import com.base.security.shiro.Principal;
import com.base.security.shiro.realm.ReamAuth;
import com.base.security.shiro.token.UsernamePasswordToken;
import com.base.util.ClassUtils;
import com.base.util.StringUtil;
import com.base.web.annotation.LoginMethod;
import com.item.dao.model.*;
import com.item.service.MobileVerifyService;
import com.item.service.RightService;
import com.item.service.UserOauthService;
import com.item.service.UserService;
import com.item.util.RoleUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ShiroAuth implements ReamAuth{
    private Logger logger = LoggerFactory.getLogger(ShiroAuth.class);

    @Autowired
    private RightService rightService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserOauthService oauthService;
    @Autowired
    private MobileVerifyService verifyService;

    /**
     * 后台用户登录走这里
     * @return
     */
    public Principal sessionUser(UsernamePasswordToken token) {
        String password = new String(token.getPassword());
        UserGroup group = RoleUtil.getGroupByCode(token.getGroup());
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("account", token.getUsername());
        params.put("password", password);
        Object object;
        try {
            object = ClassUtils.invokeMethod(group.getClassName(), "login", params);
        } catch (Exception e) {
            logger.error(token.getClassName() + "中没有定义login(account,password)方法");
            return null;
        }
        Principal principal;
        if (object != null) {
            principal = new Principal();

            Integer id;
            String roleCode;
            Integer storeId = 0;
            String name;
            Admin admin = (Admin) object;
            id = admin.getId();
            roleCode = admin.getRoleCode();
            name = admin.getName();
//			if (object instanceof Store) {
//				Store store = (Store)object;
//				id = store.getId();
//				roleCode = store.getRoleCode();
//				storeId = store.getId();
//				if (store.getType() == 4){
//					storeId = store.getParentId();
//				}
//				name = store.getName();
//			} else {
//				Admin admin = (Admin)object;
//				id = admin.getId();
//				roleCode = admin.getRoleCode();
//				name = admin.getName();
//			}
            try {
                principal.setId(id);
                principal.setRoleCode(roleCode);
                principal.setAccount(token.getUsername());
                principal.setGroupCode(token.getGroup());
                principal.setOrgName("平台管理员");
                principal.setStoreId(storeId);
                principal.setAreaCode(admin.getAreaCode());
                principal.setName(name);
                principal.setStoreId(admin.getOrgId());
                principal.setAdminType(admin.getType());
                principal.setLoginMethod(LoginMethod.ADMIN);
                if (admin.getType() == 3) {
//					Store org = storeService.selectByPrimaryKey(admin.getOrgId());
//					principal.setOrgId(admin.getOrgId()+"");
//					principal.setOrgName(org.getName());
                } else {
                }

                List<Right> rights = null;
                if (StringUtils.isBlank(roleCode)) {
                    if (StringUtils.isNotBlank(admin.getRights())) {
                        rights = rightService.selectByUser(admin.getId());
                    }
                } else {
                    Role role = RoleUtil.getRoleByCode(roleCode);
                    if (role == null) {
                        return null;
                    }
                    ShiroRole shiroRole = new ShiroRole();
                    shiroRole.setCode(role.getCode());
                    shiroRole.setId(role.getId().toString());
                    shiroRole.setName(role.getName());
                    principal.addRole(shiroRole);
                    rights = RoleUtil.getRightsByCode(group.getCode(), roleCode);
                    if (!RoleUtil.isGroupRole(roleCode, token.getGroup())) {
                        return null;
                    }
                }
                List<ShiroRight> realRight = new ArrayList<>();
                List<ShiroRight> menu = new ArrayList<>();
                if (rights != null) {
                    for (Right right : rights) {
                        if (right == null) {
                            continue;
                        }
                        ShiroRight real = new ShiroRight();
                        real.setCode(right.getCode());
                        real.setIcon(right.getIcon());
                        real.setId(right.getId().toString());
                        real.setName(right.getName());
                        real.setParentId(right.getParentId().toString());
                        real.setUrl(right.getUrl());
                        if (right.getLevel() == 3) {
                            menu.add(real);
                        } else {
                            realRight.add(real);
                        }
                    }
                }

                //添加菜单权限
                principal.setRights(realRight);
                //添加按钮权限
                principal.setMenus(menu);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("对象没有定义id或者roleCode字段");
                principal = null;
            }
        }else{
            principal = null;
        }
        return principal;
    }

    /**
     * web用户登录走这里
     * @return
     */
    public Principal webUser(UsernamePasswordToken token){
        User user = null;
        UserExample example = new UserExample();
        //普通登录
        String password = new String(token.getPassword());
        if (CaptchaEnum.WEB.getCap().equals(token.getClassName())){
            example.createCriteria().andAccountEqualTo(token.getUsername()).andPasswordEqualTo(password);
            List<User> list = userService.selectByExample(example);
            if (list.size() > 0){
                user = list.get(0);
            }
        }else if (CaptchaEnum.PHONE.getCap().equals(token.getClassName())){
            example.createCriteria().andAccountEqualTo(token.getUsername());
            List<User> list = userService.selectByExample(example);
            if (list.size() > 0){
                user = list.get(0);
            }else{
                //新建用户
                user = userService.regist(token.getUsername(), null,
                        StringUtil.formatPhone(token.getUsername()));
            }
        }else if (CaptchaEnum.OAUTH.getCap().equals(token.getClassName())){
            Integer type = Integer.parseInt(token.getGroup());
            UserOauthExample oauthExample = new UserOauthExample();
            oauthExample.createCriteria().andOpenIdEqualTo(token.getUsername()).andTypeEqualTo(type);
            List<UserOauth> list = oauthService.selectByExample(oauthExample);

            boolean insert = false;// 是否需要添加
            if (list.size() > 0) {
                UserOauth oauth = list.get(0);
                user = userService.selectByPrimaryKey(oauth.getUserId());
                if (user == null) {
                    oauthService.deleteByPrimaryKey(oauth.getId());
                    insert = true;
                }
            } else {
                insert = true;
            }
            if (insert){
                user = oauthService.oauthRegist(type,token.getUsername(),password);
            }
        }

        if(user == null){
            return null;
        }
        MobileInfo mobileInfo = new MobileInfo();
        mobileInfo.setMultiLogin(false);
        mobileInfo.setUserid(user.getId());
        mobileInfo.setDeviceType(0);
        mobileInfo.setDeviceid(user.getId().toString());
        String verify = verifyService.updateMobileVerify(mobileInfo,0,null);

        com.item.frame.Principal principal = new com.item.frame.Principal();
        principal.setGroupCode(LoginMethod.WEB.getName());
        principal.setId(user.getId());
        principal.setName(user.getNickName());
        principal.setAccount(user.getAccount());
        principal.setHeadImg(user.getHeadImg());
        principal.setState(user.getUserType());
        principal.setVip(user.getIsVip());
        principal.setLevel(user.getUserState());
        principal.setVerify(verify);
        principal.setLoginMethod(LoginMethod.WEB);
        return principal;
    }

    /**
     * h5用户登录走这里
     * @return
     */
    public Principal wapUser(UsernamePasswordToken token){
        return null;
    }

    @Override
    public Object invoke(UsernamePasswordToken token) {
        if (StringUtil.equals(token.getCaptcha(),LoginMethod.PHONE.getName())){
            return wapUser(token);
        }else if (StringUtil.equals(token.getCaptcha(),LoginMethod.WEB.getName())){
            return webUser(token);
        }else{
            return sessionUser(token);
        }
    }
}
